package cn.kgc.musicserver.controller;


import cn.hutool.core.util.ObjUtil;
import cn.kgc.musicserver.domain.dto.Result;
import cn.kgc.musicserver.domain.dto.ResultEnum;
import cn.kgc.musicserver.domain.dto.ResultUtil;
import cn.kgc.musicserver.domain.entity.ListSong;
import cn.kgc.musicserver.domain.entity.Song;
import cn.kgc.musicserver.domain.entity.SongList;
import cn.kgc.musicserver.service.IListSongService;
import cn.kgc.musicserver.service.ISongListService;
import cn.kgc.musicserver.service.ISongService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 歌单 前端控制器
 * </p>
 *
 * @author 王玉林
 * @since 2025-06-21
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/song-list")
public class SongListController {
    private final ISongListService songListService;
    private final IListSongService listSongService;
    private final ISongService songService;
    // 获取歌单列表
    @RequestMapping("page")
    public Result getSongListPage(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                  @RequestParam(value = "size", defaultValue = "5") int size,
                                  @RequestParam(value = "search", required = false) String search) {
        IPage<SongList> page = new Page<>(pageNo, size);
        page = songListService.page(page, search != null ? new QueryWrapper<SongList>().like("title", search) : null);
        return ResultUtil.returnDataSuccess(page);
    }

    @GetMapping("/list")
    public Result getSongListPage() {
        List<SongList> songList = songListService.list();
        return ResultUtil.returnDataSuccess(songList);
    }

    @RequestMapping("all")
    public Result getAllSongLists() {
        List<SongList> allSongLists = songListService.list(); // 查询全部
        return ResultUtil.returnDataSuccess(allSongLists);
    }
    /**
     * 获取歌单详情
     */
    @GetMapping("detail/{id}")
    public Result getSongListDetail(@PathVariable Integer id) {
        SongList songList = songListService.getById(id);
        if (ObjUtil.isNull(songList)) {
            return ResultUtil.returnResult(ResultEnum.FAIL_PARAM);
        }
        return ResultUtil.returnDataSuccess(songList);
    }

    /**
     * 添加歌单
     */
    @PostMapping("add")
    public Result addSongList(@RequestBody SongList songList) {
        boolean res = songListService.saveOrUpdate(songList);
        if (!res) {
            return ResultUtil.returnFail("添加失败");
        }
        return ResultUtil.returnSuccess("添加成功");
    }

    @GetMapping("delete/{id}")
    public Result deleteSongListById(@PathVariable Long id) {
        if (ObjUtil.isNull(id)) {
            return ResultUtil.returnResult(ResultEnum.FAIL_PARAM);
        }

        boolean removed = songListService.removeById(id);
        if (removed) {
            return ResultUtil.returnSuccess("删除成功");
        } else {
            return ResultUtil.returnFail("删除失败或歌单不存在");
        }


    }


    /**
     * 获取某个歌单下的歌曲列表（包含歌曲详细信息）
     */

    @GetMapping("songs/detail/{songListId}")
    public Result getSongDetailsBySongListId(@PathVariable Integer songListId) {
        if (songListId == null || songListId <= 0) {
            return ResultUtil.returnResult(ResultEnum.FAIL_PARAM);
        }

        List<ListSong> listSongs = listSongService.list(new QueryWrapper<ListSong>()
                .eq("song_list_id", songListId));

        if (listSongs == null || listSongs.isEmpty()) {
            return ResultUtil.returnDataSuccess(Collections.emptyList());
        }

        List<Integer> songIds = listSongs.stream()
                .map(ListSong::getSongId)
                .collect(Collectors.toList());

        // 查询歌曲详细信息
        List<Song> songs = songService.listByIds(songIds);

        return ResultUtil.returnDataSuccess(songs);
    }


    @GetMapping("songs/delete")
    public Result removeSongFromSongList(@RequestParam("songListId") Integer songListId,
                                         @RequestParam("songId") Integer songId) {

        if (songListId == null || songId == null) {
            return ResultUtil.returnResult(ResultEnum.FAIL_PARAM);
        }

        // 删除关联记录
        QueryWrapper<ListSong> wrapper = new QueryWrapper<>();
        wrapper.eq("song_list_id", songListId).eq("song_id", songId);
        System.out.println(songListId+"+"+songId);
        boolean removed = listSongService.remove(wrapper);
        return removed ? ResultUtil.returnSuccess("删除成功") : ResultUtil.returnFail("删除失败");
    }


}
